<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="cpnName">
        <el-input
            v-model="queryParams.cpnName"
            placeholder="请输入名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTimeRange">
        <el-date-picker
            clearable
            v-model="createTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleCreateTimeChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="用途" prop="drawType">
        <el-select v-model="queryParams.drawType" placeholder="请选择用途" clearable>
          <el-option
              v-for="dict in t_cpn_draw_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上下架" prop="isPublish">
        <el-select v-model="queryParams.isPublish" placeholder="请选择上下架" clearable>
          <el-option
              v-for="dict in t_publish_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:tcpn:add']"
        >新增
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cpnList" @selection-change="handleSelectionChange">
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="名称" align="center" prop="cpnName"/>
      <el-table-column label="用途" align="center" prop="drawType">
        <template #default="scope">
          <dict-tag :options="t_cpn_draw_type" :value="scope.row.drawType"/>
        </template>
      </el-table-column>
      <el-table-column label="有效期" align="center" prop="effTypeLabel"/>
      <el-table-column label="条件与优惠" align="center" prop="limitCondLabel"/>
      <el-table-column label="售价" align="center" prop="price"/>
      <el-table-column label="适用范围" align="center" prop="limitValueLabel"/>
      <el-table-column label="限购" align="center" prop="limitTimes"/>
      <el-table-column label="数量" align="center" prop="cpnNum"/>
      <el-table-column label="剩余库存" align="center" prop="remainCpnNum"/>
      <el-table-column label="待使用" align="center" prop="cpnUnUseNum"/>
      <el-table-column label="已使用" align="center" prop="cpnUsedNum"/>
      <el-table-column label="已过期" align="center" prop="cpnExpedNum"/>
      <el-table-column label="上下架" align="center" prop="isPublish">
        <template #default="scope">
          <dict-tag :options="t_publish_type" :value="scope.row.isPublish"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleCopy(scope.row, scope.index)"
                     v-hasPermi="['system:tcpn:copy']">
            复制
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:tcpn:remove']">删除
          </el-button>
          <el-button link type="primary" icon="Finished" @click="handlePublish(scope.row)"
                     :class="{'but-disabled': !(scope.row.isPublish === 0)}"
                     v-if="scope.row.isPublish === 0"
                     v-hasPermi="['system:tcpn:publish']">上架
          </el-button>
          <el-button link type="primary" icon="DocumentDelete" @click="handleCancelPublish(scope.row)"
                     :class="{'but-disabled': !(scope.row.isPublish === 1)}"
                     v-if="scope.row.isPublish === 1"
                     v-hasPermi="['system:tcpn:publish']">下架
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改优惠券列表对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="cpnRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="名称" prop="cpnName">
              <el-input v-model="form.cpnName" placeholder="请输入名称" maxlength="80"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用途" prop="drawType">
              <el-select v-model="form.drawType" placeholder="请选择用途" @change="handleChange">
                <el-option
                    v-for="dict in t_cpn_draw_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择类型">
                <el-option
                    v-for="dict in t_cpn_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="cpnNum">
              <el-input-number v-model="form.cpnNum" :max="9999" :min="0" step-strictly/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.drawType!=2">
            <el-form-item label="售价" prop="price">
              <el-input-number v-model="form.price" :max="999999" :min="0.01" :precision="2"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效期" prop="effTime">
              <el-input-number v-model="form.effTime" :max="999999" :min="1" step-strictly/>
              天内有效
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="最低消费" prop="minAmount">
              <el-input-number v-model="form.minAmount" :max="999999" :min="0.01" :precision="2"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优惠金额" prop="disAmount">
              <el-input-number v-model="form.disAmount" :max="999999" :min="0.01" :precision="2"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="适用范围" prop="limitValueList">
              <el-checkbox-group v-model="form.limitValueList">
                <el-checkbox v-for="dict in t_cpn_limit_value" :key="dict.value" :label="dict.value"
                             @change="(val) => handleCheckboxChange(val, dict.value)">{{
                    dict.label
                  }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.drawType!=2">
            <el-form-item label="限购次数" prop="limitTimes">
              <el-input-number v-model="form.limitTimes" :max="9999" :min="0" step-strictly/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上下架" prop="isPublish">
              <el-radio-group v-model="form.isPublish">
                <el-radio v-for="dict in t_publish_type" :key="dict.value" :label="parseInt(dict.value)">{{
                    dict.label
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="cpnDesc">
              <el-input v-model="form.cpnDesc" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Cpn">
import {listCpn, getCpn, delCpn, addCpn, updateCpn, updatePublish} from "@/api/system/cpn";
import {ref} from "vue";
import {ElMessage} from "element-plus";

const {proxy} = getCurrentInstance();
const {
  t_cpn_draw_type,
  t_publish_type,
  t_cpn_type,
  t_cpn_limit_value
} = proxy.useDict('t_cpn_draw_type', 't_publish_type', 't_cpn_type', 't_cpn_limit_value');


const cpnList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const createTimeRange = ref([]);
const isCopy = ref(0)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    cpnName: undefined,
    cpnDesc: undefined,
    type: undefined,
    cpnNum: undefined,
    limitTimes: undefined,
    startTime: undefined,
    endTime: undefined,
    drawType: undefined,
    effType: undefined,
    effTime: undefined,
    effStartTime: undefined,
    effEndTime: undefined,
    isFree: undefined,
    price: undefined,
    minAmount: undefined,
    disAmount: undefined,
    limitType: undefined,
    limitValue: undefined,
    prodId: undefined,
    status: undefined,
    statusReason: undefined,
    auditTime: undefined,
    auditor: undefined,
    ext1: undefined,
    ext2: undefined,
    ext3: undefined,
    state: undefined,
    creator: undefined,
    modifyTime: undefined,
    modifier: undefined
  },
  rules: {
    cpnName: [
      {required: true, message: "名称不能为空", trigger: "blur"}
    ],
    type: [
      {required: true, message: "类型不能为空", trigger: "change"}
    ],
    cpnNum: [
      {required: true, message: "数量不能为空", trigger: "blur"}
    ],
    price: [
      {required: true, message: "售价不能为空", trigger: "blur"}
    ],
    effTime: [
      {required: true, message: "有效期不能为空", trigger: "blur"}
    ],
    drawType: [
      {required: true, message: "用途不能为空", trigger: "change"}
    ],
    minAmount: [
      {required: true, message: "最低消费不能为空", trigger: "blur"}
    ],
    disAmount: [
      {required: true, message: "优惠金额不能为空", trigger: "blur"}
    ],
    limitValueList: [
      {required: true, message: "适用范围不能为空", trigger: "blur"}
    ],
    limitTimes: [
      {required: true, message: "限购次数不能为空", trigger: "blur"}
    ],
    isPublish: [
      {required: true, message: "上下架不能为空", trigger: "change"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

const allLimitValueList = computed(() => {
  var allLimitValueListTmp = [];
  for (let dict of t_cpn_limit_value.value) {
    allLimitValueListTmp.push(dict.value);
  }
  return allLimitValueListTmp;
})

function handleCheckboxChange(value, keyValue) {
  if (keyValue == "0") {
    if (value) {
      form.value.limitValueList = allLimitValueList.value;
    } else {
      form.value.limitValueList = [];
    }
  } else {
    if (value) {
      if (form.value.limitValueList.includes("0")) {
        form.value.limitValueList = allLimitValueList.value;
      } else {
        if (form.value.limitValueList.length == 4) {
          form.value.limitValueList = allLimitValueList.value;
        }
      }
    } else {
      if (form.value.limitValueList.includes("0")) {
        form.value.limitValueList = form.value.limitValueList.filter(item => item !== "0");
      }
    }
  }
}

/** 查询优惠券列表列表 */
function getList() {
  loading.value = true;
  listCpn(queryParams.value).then(response => {
    cpnList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  reset();
  open.value = false;
  getList()
}

// 表单重置
function reset() {
  form.value = {
    cpnId: undefined,
    cpnName: undefined,
    cpnDesc: undefined,
    type: 1,
    cpnNum: 0,
    limitTimes: 0,
    startTime: undefined,
    endTime: undefined,
    drawType: 1,
    effType: undefined,
    effTime: undefined,
    effStartTime: undefined,
    effEndTime: undefined,
    isFree: undefined,
    price: undefined,
    minAmount: undefined,
    disAmount: undefined,
    limitType: undefined,
    limitValue: undefined,
    limitValueList: allLimitValueList.value,
    prodId: undefined,
    isPublish: 1,
    status: undefined,
    statusReason: undefined,
    auditTime: undefined,
    auditor: undefined,
    ext1: undefined,
    ext2: undefined,
    ext3: undefined,
    state: undefined,
    createTime: undefined,
    creator: undefined,
    modifyTime: undefined,
    modifier: undefined
  };
  proxy.resetForm("cpnRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  createTimeRange.value = [];
  queryParams.value.createStartTime = null;
  queryParams.value.createEndTime = null;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.cpnId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  isCopy.value = 0
  open.value = true;
  title.value = "添加优惠券";
}

/** 复制按钮操作 */
function handleCopy(row) {
  reset();
  // row.cpnId = null;
  isCopy.value = 1
  form.value = row;
  open.value = true;
  title.value = "复制优惠券";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _cpnId = row.cpnId || ids.value
  getCpn(_cpnId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改优惠券";
  });
}

/** 提交按钮 */
function submitForm() {
  if (form.value.price > form.value.disAmount) {
    ElMessage.error('售价不能大于优惠金额哦！')
    return
  }
  if (form.value.minAmount < form.value.disAmount) {
    ElMessage.error('最低消费不能小于优惠金额哦！')
    return
  }

  // 如果是复制功能的话，把form中的cpnId去掉
  if (isCopy._value == 1) {
    form.value.cpnId = null
  }

  proxy.$refs["cpnRef"].validate(valid => {
    if (valid) {
      if (form.value.cpnId != null) {
        updateCpn(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCpn(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _cpnIds = row.cpnId || ids.value;
  proxy.$modal.confirm('是否确认删除优惠券列表编号为"' + _cpnIds + '"的数据项？').then(function () {
    return delCpn(_cpnIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/cpn/export', {
    ...queryParams.value
  }, `cpn_${new Date().getTime()}.xlsx`)
}

function handleCreateTimeChange(value) {
  if (value && value.length === 2) {
    queryParams.value.createStartTime = value[0];
    queryParams.value.createEndTime = value[1];
  } else {
    queryParams.value.createStartTime = null;
    queryParams.value.createEndTime = null;
  }
}

function handlePublish(row) {
  const _merIds = row.merId || ids.value;
  proxy.$modal.confirm('是否确认上架优惠券，编号为"' + _merIds + '"的数据项？').then(function () {
    row.isPublish = 1;
    return updatePublish(row);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("上架成功");
  }).catch(() => {
  });
}

function handleCancelPublish(row) {
  const _merIds = row.merId || ids.value;
  proxy.$modal.confirm('是否确认下架优惠券，编号为"' + _merIds + '"的数据项？').then(function () {
    row.isPublish = 0;
    return updatePublish(row);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("下架成功");
  }).catch(() => {
  });
}

function handleChange(value) {
  if (value === 2) {
    form.value.price = null;
    form.value.limitValue = null;
  }
}

onActivated(() => {
  getList();
})
getList();
</script>
